<?php

/**
 * @Author: 刘洪
 * @Date:   2018-11-20 13:29:21
 * @Last Modified by:   user
 * @Last Modified time: 2019-01-07 11:32:53
 */
namespace app\common\remind;

use think\Db;
use think\Log;

/**
 * 任务提醒类
 * @access public
 */
class RemindTask extends RemindMain
{
	/**
	 * 任务提醒类型
	 * @access protected
	 * @var integer
	 */
	protected $remindType=0;

	/**
	 * 提醒列表
	 * @access private
	 * @var array
	 */
	private $remindList=[];
	/**
	 * 任务状态
	 * @access private
	 * @var [type]
	 */
	private $task_status=['已启动','未启动','已完成','延迟','关闭','关闭','关闭','关闭'];


	/**
	 * 构造方法
	 */
	function __construct(){

	}

	/**
	 * 实例调用入口方法
	 * @access public
	 */
	public function index(){
		//初始化方法
		$this->remindList=parent::init();

		//执行数据重组方法
		$this->regroupData();

		//执行发送
		parent::send("任务");
		
	}

	/**
	 * 实现父类抽象方法
	 * @access protected
	 * @return [type] [description]
	 */
	protected function regroupData()
	{
		//arr[]=[trigger,send_type,receives,send_connect]
		//		[触发类型[]，发送方式，接收人[]，发送内容[]]
		
		foreach ($this->remindList as $arr) {
			switch($arr['trigger']){
				case 0://新增任务查询条件
						//条件：创建时间 和 当前时间 差  小于等于发送 周期

					$where="TIMESTAMPDIFF(MINUTE,FROM_UNIXTIME(`create_time`),now())<=".$this->period*60;

					//echo "新增触发条件开始\n";

				break;
				case 1://修改任务
						//条件：修改时间  和 当前时间差  小于等于发送周期

					$where="TIMESTAMPDIFF(MINUTE,FROM_UNIXTIME(`modify_time`),now())<=".$this->period*60;

					//echo "修改触发条件开始\n";

				break;
				case 2://删除任务
						//修改【时间为-288  发送完后修改为 -28800 舍弃此种做法
					$where="2";

					//echo "删除触发条件开始\n";

				break;
				case 3://任务截至前
						//已启动的任务中 条件：任务截至前第3天 并且 是当天第一次提醒  当前时间大于等于截止前时间
					if($this->is_first){
						$where="`status`=0 and deadline>=unix_timestamp(now()) and TIMESTAMPDIFF(DAY,FROM_UNIXTIME(`deadline`,'%Y-%m-%d'),now())%3=0";

						//echo "任务截至前触发条件开始\n";
					}					
				break;

				case 4://超期任务
						//已启动的任务中 截至时间<=今天  并且 截至时间和当前时间差取余%3=0  隔3天提醒一次  当天第一次提醒
					if($this->is_first){
						$where='`status`=0 and deadline<=unix_timestamp(now()) and TIMESTAMPDIFF(DAY,FROM_UNIXTIME(`deadline`,"%Y-%m-%d"),now())%3=0';

						//echo "任务超期触发条件开始\n";
					}
					break;

				case  5://日志更新提醒
					//echo '日志更新提醒执行';
					$where="";//'`task_id=(select task_id from `cmf_log` where TIMESTAMPDIFF(MINUTE,FROM_UNIXTIME(`add_time`),now())<='.$this->period*60." order by `add_time` desc limit 0,1)";
					break;

				}	


				if(isset($where)){
					Log::write('任务提醒触发sql条件'.$where);
					Log::write('触发类型：'.$arr['trigger']);
					//如果是删除的任务提醒   
					if($where=="2"){
						$task=[];
        				$fp=fopen(APP_PATH."common/remind/delete.json",'r');
        				if(file_exists(APP_PATH."common/remind/delete.json")){
            				while(!feof($fp)){
                			$k=fgets($fp);
                			$task[]=json_decode($k);
            				}
        				}
        				fclose($fp);
        				//读取完成后清空文件
        				file_put_contents(APP_PATH."common/remind/delete.json","");
        				//卸载条件变量
        				unset($where);

					}else{

						//日志更新提醒
						if($arr['trigger']==5){
							//$log=Db::query("SELECT * FROM `cmf_log` where  group by task_id  order by  add_time desc");
							$log=Db::table('cmf_log')->where("TIMESTAMPDIFF(MINUTE,FROM_UNIXTIME(`add_time`),now())<=".$this->period*60)->order('add_time desc')->group('task_id')->select();
							$task=[];
							foreach ($log as $l) {
								dump($l);
								$t=Db::name('task')->where('task_id',$l['task_id'])->find();
								$t['describe']=$l['con'];
								$task[]=$t;
							}

							//dump($task);
						}else{//
							$task=Db::query("SELECT * FROM `cmf_task` where ".$where);//table('cmf_task')->where($where)->select();//获取任务表中数据
						}
					}

					if(!empty($task)){
						//格式数据 放入发送列表 $this->sendList;
						$this->formatSendList($task,$arr);
					}else{
						Log::write('本次无任务提醒内容： 触发类型：'.$arr['trigger']);
					}	
				}		

			}
		}


		/**
		 * 数据格式化
		 * @access protected
		 * @param  array $task 任务数据
		 * @param  array $arr  需要提醒的项
		 * @return 无
		 */
		protected function formatSendList($task,$arr)
		{
			$status=[' (新增)',' (已修改)',' (已删除)',' (即将到期)',' (已超期','日志更新'];

			//标题
			$title="";
			switch ($arr['trigger']) {
				case 0:
				$title='新增任务提醒';
				break;
				case 1:
				$title='修改任务提醒';
				break;
				case 2:
				$title='删除任务提醒';
				break;
				case 3:
				$title='到期任务提醒';
				break;
				case 4:
				$title='超期任务提醒';
				break;	
				case 5:
				$title='任务日志更新提醒';
				break;		
			}
			//遍历任务列表
			foreach ($task as $it) {
				if(empty($it)) continue;
				//获取要发送的内容
				//send_connect['发布人','相关人','处理人','负责人','标题','状态','截至时间','任务内容']
				$send_connect="<div style='background-color:#ccc;margin-top:10px;'><h3>".$title."</h3>";
				//短信内容
				$sms_connect=$it['tit'].$status[$arr['trigger']];

				$today=date('Ymd',time());
				$dealday=date('Ymd',$it['deadline']);
				if($arr['trigger']==4){
					$sms_connect.=($today-$dealday)."天)";
				}
				$sms_connect.="(".$this->task_status[$it['status']].")";

				foreach ($arr['send_connect'] as $key) {

					if($key==4){
						$send_connect.="<div>标题：".$it['tit']."</div>";
					}
					if($key==5){
						$send_connect.="<div>状态：".$this->task_status[$it['status']]."</div>";
					}
					if($key==0){
						$send_connect.="<div>发布人：".$it['release_name']."</div>";
					}
					if($key==1){
						$send_connect.="<div>相关人：".$it['rela_name']."</div>";
					}
					if($key==2){
						$send_connect.="<div>处理人：".$it['deal_name']."</div>";
					}
					if($key==3){
						$send_connect.="<div>负责人：".$it['learder_name']."</div>";
					}
					
					if($key==6){
						$send_connect.="<div>截止时间：".date('Y-m-d H:i:s',$it['deadline'])."</div>";
					}
					if($key==7){
						$str=cmf_replace_content_file_url(htmlspecialchars_decode($it['describe']));
						$send_connect.="<div>内容：".$str."</div>";
					}
				}
				$send_connect.="</div>";

				//接收人
				$receives="";
				foreach ($arr['receives'] as $key) {
					if($key==0){
						$receives.=$it['release'].",";
					
					}
					if($key==1){
						$receives.=$it['rela'].",";

					}
					if($key==2){
						$receives.=$it['deal'].",";
					}
					if($key==3){
						$receives.=$it['learder'].",";
					}
				}
				//接收人id 过滤数组去重复
				$receives 	= array_unique(array_filter(explode(',',$receives)));

				foreach ($receives as $k=>$value) {//遍历接收人id
					foreach ($this->admin_users as $v) {//遍历后台员工
						if(intval($value) === $v['id']){//如果接收人id==后台员工id

							if($arr['send_type'] == 1 || $arr['send_type']==0){//邮件

								if(!isset($this->sendList['email'][$v['user_email']])){
									$this->sendList['email'][$v['user_email']]="";
								}	
								$this->sendList['email'][$v['user_email']]	.=	$send_connect;
							}
							if($arr['send_type'] == 2 || $arr['send_type']==0){//电话

								if(!isset($this->sendList['mobile'][$v['mobile']])){
									$this->sendList['mobile'][$v['mobile']]="";
								}	
								$this->sendList['mobile'][$v['mobile']]	.="(".$sms_connect.");";
							}

						}

					}
				}



			}

		}


	}